/**
 * @FileName: HttpClient.java
 * @author wangshangyu
 * @date 2014-9-18 ����05:39:53
 * @version 1.0
 */
package com.raptor.trustworthycore.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * @description http请求类
 * @author wusuhuan
 * @date 2015-8-23下午6:47:52
 * @version 1.0
 */
public class HttpClients {

	public HttpClients() {
	}

	/**
	 * get请求
	 *
	 * @param url
	 * @param params
	 * @return
	 */
	public static String httpGet(String url, Map<String, String> params) {
		String result = "";
		try {
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			for (String key : params.keySet()) {
				list.add(new BasicNameValuePair(key, params.get(key)));
			}
			String str = EntityUtils.toString(new UrlEncodedFormEntity(list,
					HTTP.UTF_8));
			url = url + "?" + str;
			HttpURLConnection hcon = (HttpURLConnection) new URL(url)
					.openConnection();
			hcon.setDoOutput(true);
			hcon.setRequestMethod("GET");
			hcon.setRequestProperty("Content-Type",
					"application/json;charset=UTF-8");
			hcon.setRequestProperty("user-Agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			hcon.connect();
			InputStream is = hcon.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			String line = null;
			while ((line = br.readLine()) != null) {
				result += line;
			}
			is.close();
			// 断开连接
			hcon.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * post请求
	 *
	 * @param url
	 * @param param
	 * @return
	 */
	public static String httpPost(String url, String param) {
		String result = "";
		try {
			HttpURLConnection hcon = (HttpURLConnection) new URL(
					url).openConnection();
			hcon.setDoInput(true);
			hcon.setDoOutput(true);
			hcon.setUseCaches(false);
			hcon.setRequestMethod("POST");
			hcon.setConnectTimeout(3000);
			hcon.setRequestProperty("Accept", "*/*");
			hcon.setRequestProperty("Connection", "Keep-Alive");
			hcon.setRequestProperty("Content-type",
					"application/x-java-serialized-object");
			hcon.setRequestProperty("Content-Type",
					"application/html;charset=UTF-8");
			hcon.setRequestProperty("user-Agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			hcon.connect();

			java.io.PrintWriter out = new java.io.PrintWriter(
					new java.io.OutputStreamWriter(hcon.getOutputStream(),
							"UTF-8"));
			out.write(param);
			out.flush();
			out.close();

			BufferedReader in = new BufferedReader(
					new InputStreamReader(hcon.getInputStream(),
							"UTF-8"));
			// 读取服务器对于此次http请求的返回信息
			String line = null;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			in.close();
			// 断开连接
			hcon.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取request ip
	 *
	 * @param request
	 * @return
	 */
	public static String getIpAddress(HttpServletRequest request) {

		String ipAddress = request.getHeader("x-forwarded-for");

		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknow".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();

			if (ipAddress.equals("127.0.0.1")
					|| ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡获取本机配置的IP地址
				InetAddress inetAddress = null;
				try {
					inetAddress = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inetAddress.getHostAddress();
			}
		}

		// 对于通过多个代理的情况，第一个IP为客户端真实的IP地址，多个IP按照','分割
		if (null != ipAddress && ipAddress.length() > 15) {
			// "***.***.***.***".length() = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

//	public static void main(String[] args) {
//		Map<String, String> map = new HashMap<String, String>();
//		map.put("current_page", "1");
//		map.put("rows_of_page", "10");
//		map.put("company_code", "001");
//		map.put("phone", "15366166145");
//		map.put("start_order_time", "2018-01-01");
//		map.put("end_order_time", "2018-03-01");
//		map.put("query_type", "");
//		map.put("order_status", "");
//		map.put("sign", "0b3054cb09443468da694326da28a6d4");
//		map.put("area_code", "32");
//		httpGet("http://202.102.39.15/besttone.support/consume/query_fee", map);
//	}

}
